package com.woniuxy.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.lang.func.Func1;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.core.exception.accountException.AccountException;
import com.woniuxy.core.exception.accountException.AccountExceptionCode;
import com.woniuxy.core.exception.certifiedException.CertifiedException;
import com.woniuxy.core.exception.certifiedException.CertifiedExceptionCode;
import com.woniuxy.core.staticCode.UserCode;
import com.woniuxy.core.util.HttpUtils;
import com.woniuxy.core.util.OSSUtil;
import com.woniuxy.core.util.PageInfo;
import com.woniuxy.user.dao.UserAccount;
import com.woniuxy.user.dao.UserInfo;
import com.woniuxy.user.mapper.UserAccountMapper;
import com.woniuxy.user.mapper.UserInfoMapper;
import com.woniuxy.user.model.param.IdCard;
import com.woniuxy.user.model.param.LoadAllUserinfoParam;
import com.woniuxy.user.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 凌玉春
 * @since 2024年01月15日
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserAccountMapper userAccountMapper;

    @Resource
    private OSSUtil ossUtil;

    @Override
    public IdCard VerifyIdCard(String name , String idcard, Integer id , String userInfoName) {
        System.out.println("sssssssssssssssssssssssssssssssssssssssssssssssssssssss");
        String host = "https://sfzsmyxb.market.alicloudapi.com";
        String path = "/get/idcard/checkV3";
        String method = "GET";
        String appcode = "c3066463eafd426abc402c8e9dea9709";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("name", name);
        querys.put("idcard", idcard);


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            System.out.println("-----------------------------------------");
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println(responseBody);

            JSONObject jsonObject = JSONObject.parseObject(responseBody);
            int code = jsonObject.getIntValue("code");
            System.out.println(code);
            String message = jsonObject.getString("message");
            System.out.println(message);
            JSONObject data = jsonObject.getJSONObject("data");
            System.out.println(data);
            cn.hutool.json.JSONObject entries = JSONUtil.parseObj(data.toJSONString());
            System.out.println("```````````````````");
            System.out.println(entries);
            if (code == 200) {
                    String orderNo = data.getString("order_no");
                    System.out.println(orderNo);
                    String birthday = data.getString("birthday");
                    System.out.println(birthday);
                    String address = data.getString("address");
                    System.out.println(address);
                    String sex = data.getString("sex");
                    System.out.println(sex);
                    String desc = data.getString("desc");
                    System.out.println(desc);

                String birthdayString = idcard.substring(6, 14);
                LocalDate birthdays = LocalDate.parse(birthdayString, DateTimeFormatter.ofPattern("yyyyMMdd"));

               // 计算年龄
                LocalDate currentDate = LocalDate.now();
                int age = Period.between(birthdays, currentDate).getYears();

                System.out.println("年龄：" + age);

                QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("user_account_id", id);
               // 查询数据库中符合条件的一条记录
                UserInfo existingUserInfo = userInfoMapper.selectOne(wrapper);
                //已有身份证不能重复操作
                String userInfoCard = existingUserInfo.getUserInfoCard();
                if (userInfoCard!=null){
                    throw new AccountException(AccountExceptionCode.IDCARD_HAVEUSE);
                }
                //判断是否有重复的身份证
                QueryWrapper<UserInfo> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("user_info_card",idcard);
                UserInfo userInfo1 = userInfoMapper.selectOne(wrapper1);
                if (userInfo1!=null){
                    throw new AccountException(AccountExceptionCode.IDCARD_DUOCI);
                }
                if (existingUserInfo != null) {
                    // 如果存在符合条件的记录，更新其属性值
                    existingUserInfo.setUserInfoCard(idcard);
                    existingUserInfo.setUserRealName(name);
                    existingUserInfo.setUserInfoAge(age);
                    existingUserInfo.setUserRealNameState(UserCode.USER_REAL_NAME_STATE.getCode());
                    existingUserInfo.setUserInfoName(userInfoName);
                    String url = "https://car-port.oss-cn-chengdu.aliyuncs.com/1750393438211280896.png";
                    //设置默认头像
                    existingUserInfo.setUserInfoImg(url);
                    userInfoMapper.updateById(existingUserInfo);
                } else {
                    // 如果不存在符合条件的记录，创建新的 UserInfo 对象并设置属性值，然后插入数据库
                    UserInfo userInfo = new UserInfo();
                    userInfo.setUserAccountId(id);
                    userInfo.setUserInfoCard(idcard);
                    userInfo.setUserRealName(name);
                    //0是已实名
                    userInfo.setUserRealNameState(UserCode.USER_REAL_NAME_STATE.getCode());
                    userInfoMapper.insert(userInfo);
                }
                return new IdCard(true, orderNo, birthday, address, sex, desc);
            } else {
                System.out.println("sadnjknfjdn===sad");
                return new IdCard(false, null, null, null, null, message);
            }
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
            return new IdCard(false, null, null, null, null, "请求接口失败：" + e.getMessage());
        }
    }

    @Override
    public void updateUserInfo(String userinfoname, String userinfotel,Integer id) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_account_id",id);
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        userInfo.setUserInfoName(userinfoname);
        userInfo.setUserInfoTel(userinfotel);
        Integer accountId = userInfo.getUserAccountId();
        System.out.println(accountId);
        QueryWrapper<UserAccount> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id",accountId);
        UserAccount userAccount = userAccountMapper.selectOne(wrapper1);
        userAccount.setUserInfoTel(userinfotel);
        userAccountMapper.updateById(userAccount);
        userInfoMapper.updateById(userInfo);
    }

//    @Override
//    public PageInfo<UserInfo> loadAllUserinfobyId(LoadAllUserinfoByIdParam param) {
//        Page<UserInfo> page = new Page<UserInfo>(param.getPageNum() == null ? 1 : param.getPageNum(), param.getPageSize() == null ? 5 : param.getPageSize());
//        QueryWrapper<UserInfo> wrapper = new QueryWrapper<UserInfo>();
//        wrapper.eq("user_info_id",param.getUserInfoId());
//        userInfoMapper.selectPage(page,wrapper);
//        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
//        pageInfo.setList(page.getRecords());
//        pageInfo.setPages(page.getPages());
//        System.out.println(pageInfo);
//        return pageInfo;
//    }

    @Override
    public PageInfo<UserInfo> loadAllUserinfo(LoadAllUserinfoParam param) {
        Page<UserInfo> page = new Page<UserInfo>(param.getPageNum() == null ? 1 : param.getPageNum(), param.getPageSize() == null ? 5 : param.getPageSize());
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<UserInfo>();
        userInfoMapper.selectPage(page,wrapper);
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setList(page.getRecords());
        pageInfo.setPages(page.getPages());
        System.out.println(pageInfo);
        return pageInfo;
    }

        @Override
        public UserInfo loadAllUserinfobyId(Integer userInfoId) {
        if (userInfoId==null){
            throw new AccountException(AccountExceptionCode.NOT_USERINFOID_NULL);
        }

        return  userInfoMapper.selectById(userInfoId);

        }

    @Override
    public UserInfo uploadImage(MultipartFile image, String id) throws IOException {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_account_id",id);
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        //获取文件类型
        String fileType = FileTypeUtil.getType(image.getInputStream());
        if (!fileType.equals("jpg")&&!fileType.equals("png")){
            throw new CertifiedException(CertifiedExceptionCode.PICTURE_FORMAT_ERROR);
        }
        //创建文件名称
        Snowflake snowflake = new Snowflake(1,1);
        String prefix = snowflake.nextIdStr();
        String fileName = prefix+"."+fileType;
        String url = ossUtil.uploadFile(image.getInputStream(), fileName, "car-port");
        userInfo.setUserInfoImg(url);
        userInfoMapper.updateById(userInfo);
        return userInfo;
    }

    @Override
    public UserInfo loadAllUserinfobyName(String userRealName) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_real_name", userRealName);
        return userInfoMapper.selectOne(wrapper);
    }

    @Override
    public UserInfo loadAllUserinfobyUserPhone(String userphone) {
        if (userphone.length()!=11){
            throw new AccountException(AccountExceptionCode.LENTH_WORRY);
        }
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_info_tel", userphone);
        return userInfoMapper.selectOne(wrapper);
    }

    @Override
    public void updateUserState(Integer id) {
        QueryWrapper<Object> wrapper = new QueryWrapper<>();
        QueryWrapper<Object> userId = wrapper.eq("user_id", id);
        UserAccount userAccount = userAccountMapper.selectById(userId);
        Integer userState = userAccount.getUserState();
        System.out.println("---------------------");
        System.out.println(userState);
        System.out.println("---------------------");
        if (userState==1){
            userAccount.setUserState(0);
        }
        if (userState==0){
            userAccount.setUserState(1);
        }
    }

    @Override
    public UserInfo loadAllUserinfos(String id) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        if (userInfo==null){
            throw  new AccountException(AccountExceptionCode.NO_USER);
        }
        return userInfo;
    }

    @Override
    public Boolean loadAllUserinfoss(String id) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        if (ObjectUtil.isEmpty(userInfo.getUserInfoCard())){
            return false;
        }
        Integer userRealNameState = userInfo.getUserRealNameState();
        if (userRealNameState==0){
            return true;
        }else {
            return false;
        }
    }

    public static void main(String[] args) throws Exception {
        Func1<UserInfo, String> xxx = UserInfo::getUserInfoName;
        UserInfo info = new UserInfo();
        info.setUserInfoName("天年");
        String s = xxx.call(info);
        System.out.println(s);
    }
}
